package com.example.home.ui

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.recyclerview.widget.LinearLayoutManager
import com.example.home.adapter.VideoAdapter
import com.example.home.databinding.HomeFragmentBinding
import com.example.home.intent.VideoIntent
import com.example.home.model.service.VideoModel
import com.example.home.state.VideoState
import com.example.mvicore.common.CustomViewModelFactory
import com.example.mvicore.ui.BaseMVIFragment
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch

class HomeFragment:BaseMVIFragment() {

    private lateinit var model:VideoModel
    private lateinit var binding : HomeFragmentBinding
    private var page : Int = 0;
    private var pagesize:Int = 10;
    private lateinit var adapter : VideoAdapter

    override fun initView(view: View) {
        super.initView(view)
        val layoutManager: LinearLayoutManager = LinearLayoutManager(requireContext(),LinearLayoutManager.VERTICAL,false)
        binding.rvHomeHome.layoutManager = layoutManager
        this.adapter = VideoAdapter()
        binding.rvHomeHome.adapter = this.adapter

    }

    override fun collectState() {
        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){
                model.status.collect {
                    when(it){
                        is VideoState.VideoSuceess->{
                            //刷新数据
                            adapter.refresh(it.datas)
                        }
                        is VideoState.VideoFailed->{
                            getOwnActivity().showMsg(it.error.message.toString())
                        }
                        else->{}
                    }
                }
            }
        }
    }

    override fun generateViewModel() {
        model = CustomViewModelFactory(this@HomeFragment).create(VideoModel::class.java)
    }

    override fun generateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = HomeFragmentBinding.inflate(layoutInflater,container,false)
        return binding.root
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED){
                model.events.send(VideoIntent.GetRecommendVideo(page,pagesize))
            }
        }
    }
}